//
//  MPLockHelper.m
//  BBVoice
//
//  Created by Hyukooooh on 2024/10/17.
//

#import "MPLockHelper.h"
#import "CoreArchive.h"
#import "MOLockViewController.h"
#import "QAGlobalManager.h"
#import "QACMMotionManager.h"
@implementation MPLockHelper

+ (BOOL)coreArchiveBoolforKey:(NSString *)key{
    return [CoreArchive boolForKey:key];
}


+ (BOOL)hasOpenGesturesPassowrd{
    NSString *hogp = [NSString stringWithFormat:@"%@_hogp",WCICache.user.userId];
    return [CoreArchive boolForKey:hogp];
}

+ (void)openGesturesPassword:(BOOL)success {
    NSString *hogp = [NSString stringWithFormat:@"%@_hogp",WCICache.user.userId];
    [CoreArchive setBool:success key:hogp];
}

+ (BOOL)hasOpenIDPassword{
    NSString *idlock = [NSString stringWithFormat:@"%@_idlock",WCICache.user.userId];
    return [CoreArchive boolForKey:idlock];
}

+ (void)openIDPassword:(BOOL)success{
    NSString *idlock = [NSString stringWithFormat:@"%@_idlock",WCICache.user.userId];
    [CoreArchive setBool:success key:idlock];
}


+ (NSInteger)getUnregisterCount{
    NSString *unregisterCount = [NSString stringWithFormat:@"%@_unregisterCount",WCICache.user.userId];
    return [CoreArchive intForKey:unregisterCount];
}

+ (void)resetUnregisterCount:(NSInteger)count{
    NSString *unregisterCount = [NSString stringWithFormat:@"%@_unregisterCount",WCICache.user.userId];
    [CoreArchive setInt:count key:unregisterCount];
}

+ (BOOL)hasCLLockPassword{
    return [MOLockViewController hasPwd];
}

///关闭应用锁清理本地数据
+ (void)closeApplicationLockClearLocalData {
    [self clearAboutPasswordLocalValue];
}

///开启应用锁保存本地数据
+ (void)openApplicationLockSaveLocalData {
    [self openGesturesPassword:YES];
}

+ (void)clearAboutPasswordLocalValue{
    //清除锁屏是否开启锁屏验证状态
    SETUserDefaults(@(0), @"Lock_Screen");
    //清除离开应用时间
    WCICache.resignActiveTime = @0;
    //忘记或者超过次数
//    MOCache.isRemoveAppLock = @(1);
    //清除是否开启应用锁状态
    NSString *hogp = [NSString stringWithFormat:@"%@_hogp",WCICache.user.userId];
    [CoreArchive setBool:NO key:hogp];
    [CoreArchive setBool:NO key:[NSString stringWithFormat:@"%@_idlock",WCICache.user.userId]];
    [MPLockHelper resetUnregisterCount:0];
    //清除是否开启摇晃锁屏状态
    NSString *shakeLock = [NSString stringWithFormat:@"%@_sl",WCICache.user.userId];
    [CoreArchive setBool:NO key:shakeLock];
    //锁定时间60s
    WCICache.lockTime = @(60);
    //应用锁类型设置回默认状态（手势密码）
    [CoreArchive setBool:NO key:OPEN_PASSWORD_STYLE];
    //密码错误次数设置回默认状态（5次错误机会）
    [CoreArchive setInt:0 key:ERROR_TIMES];
    //清除应用锁
    if (![QAStringTool isBlankString:WCICache.user.userId]) {
        [CoreArchive removeStrForKey:WCICache.user.userId];
    }
}

#pragma mark -- 锁屏
///注册首次设置密码
+ (void)showFirstSettingLockVCInVC:(UIViewController *)vc successBlock:(void (^)(void))successBlock{
    UIViewController *currentVC = [self topViewControllerForKeyWindow];
    BOOL has = [MPLockHelper hasCLLockPassword];
    if (has) {
        if (successBlock) {
            successBlock();
        }
        return;
    }
    
    if ([currentVC isKindOfClass:[MOLockViewController class]]) {
        return;
    }
    
    MOLockViewController * lvc = [MOLockViewController showFirstSettingLockVCInVC:vc successBlock:^(MOLockViewController *lockVC, NSString *pwd) {
        [lockVC dismiss:1.0f];
        NSMutableDictionary *para = [NSMutableDictionary new];
        [para setObject:@(1) forKey:@"msg_hidden"];
        [QAModuleService updateUserInfoWithPara:para success:^(QAResponseModel *response) {
            QAUserInfoModel *userInfo = WCICache.user;
            userInfo.msg_hidden = @"1";
            WCICache.user = userInfo;
        } failure:^(QAResponseModel *response) {

        }];
        [MPLockHelper openApplicationLockSaveLocalData];
        if (successBlock) {
            successBlock();
        }
    }  closeBlock:^{
        if (successBlock) {
            successBlock();
        }
    }];
    lvc.hideLeftNavBtn = YES;
}
+ (void)judgeShowLockViewWithDoNotCareShake:(BOOL)doNotCareShake showShake:(BOOL)showShare{
    if ([[self topViewControllerForKeyWindow] isKindOfClass:[MOLockViewController class]]) {
        return;
    }
    
    if (WCICache.user.isLogin) {
        BOOL hasPwd = [MOLockViewController hasPwd];
        if (hasPwd) {
            if ([WCICache.netStatus integerValue] != 0) {
                if ([QAStringTool isBlankString:WCICache.user.msg_hidden] ||
                    [WCICache.user.msg_hidden isEqualToString:@"0"]) {
                    NSMutableDictionary *para =  [NSMutableDictionary new];
                    [para setObject:@(1) forKey:@"msg_hidden"];
                    [QAModuleService updateUserInfoWithPara:para success:^(QAResponseModel *response) {
                        QAUserInfoModel *userInfo = WCICache.user;
                        userInfo.msg_hidden = @"1";
                        WCICache.user = userInfo;
                    } failure:^(QAResponseModel *response) {
                        
                    }];
                }
            }
            
            NSString *shakeLock = [NSString stringWithFormat:@"%@_sl",WCICache.user.userId];
            BOOL isShake = [CoreArchive boolForKey:shakeLock];
            if (![[self topViewControllerForKeyWindow] isKindOfClass:[MOLockViewController class]]) {
                //用户是否锁屏
                BOOL isLockScreen = [GETUserDefaultsForKey(@"Lock_Screen") boolValue];
                if (isLockScreen) {
                    //用户手动锁屏 直接展示手势密码
                    [self _showLockView];
                    return;
                }
                
                if (doNotCareShake) {
                    //当前时间的时间戳
                    NSTimeInterval nowTime = [QAGlobalManager manager].getNowServerTime;// *1000 是精确到毫秒，不乘就是精确到秒
                    //app点击home键进入到后台或失去焦点时的时间戳
                    NSTimeInterval localTime =  [WCICache.resignActiveTime integerValue];
                    NSInteger lockTime = [WCICache.lockTime integerValue];
                    if ((localTime && nowTime - localTime > (lockTime * 1000)) || localTime == 0) {
                        [self _showLockView];
                        return;
                    }
                }
                if (isShake && showShare) {
                    [self _showLockView];
                    return;
                }
            }
        }
    }
}

//显示锁屏
+ (void)_showLockView{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CLLockVCWillShowNotification" object:nil];
    if ([[self topViewControllerForKeyWindow] isKindOfClass:[MOLockViewController class]] || MOLockViewController.isLocking) {
        
        return;
    }
    WeakSelf(ws);
    if (!WCICache.user.isLogin) {
        return;
    }
    
    UIWindow *window = [QATool getKeyWindow];
    
    MOAlerter *currentAlerter = nil;//当前视图上有显示警告框
    for (UIView *view in window.subviews.reverseObjectEnumerator) {
        if (view.tag == 88888) {
            [view removeFromSuperview];
        }
        if (/**  view.tag == 3333333333 这里只针对问个好弹窗界面  && */ [view isKindOfClass:MOAlerter.class]){
            currentAlerter = (MOAlerter *)view;
            view.hidden = YES;//有显示警告框时先隐藏警告框
        }
    }
    
    MOLockViewController * vc = [MOLockViewController showVerifyLockVCInVC:[self topViewControllerForKeyWindow] isClose:NO isPresent:YES forgetPwdBlock:^{
        NSLog(@"忘记密码");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (currentAlerter) {
                [currentAlerter hide];//忘记密码直接关闭警告框
            }
            [weakSelf clearAboutPasswordLocalValue];
            [QAModuleService logoutAction];
        });
    } successBlock:^(MOLockViewController *lockVC, NSString *pwd) {
        NSLog(@"密码正确");
        [lockVC dismiss:0.5f];
        if (currentAlerter) {
            currentAlerter.hidden = NO;//密码正确恢复显示警告框
        }
        [[QACMMotionManager shareInstance] startAccelerometer];
    }];
    vc.hideDismissAnimated = YES;
}
+ (void)closeApplicationLockShowInVc:(UIViewController *)viewController forgetPwdBlock:(void(^)(void))forgetPwdBlock successBlock:(void (^)(NSString *pwd))successBlock {
    [MOLockViewController showVerifyLockVCInVC:viewController isClose:YES isPresent:NO forgetPwdBlock:^{
        [MPLockHelper clearAboutPasswordLocalValue];
        if (forgetPwdBlock) {
            forgetPwdBlock();
        }
    } successBlock:^(MOLockViewController *lockVC, NSString *pwd) {
        [lockVC dismiss:0.1f];
        if (successBlock) {
            successBlock(pwd);
        }
    }];
}

+ (void)openApplicationLockShowInVc:(UIViewController *)viewController successBlock:(void (^)(NSString *pwd))successBlock {
    [MOLockViewController showSettingLockVCInVC:viewController successBlock:^(MOLockViewController *lockVC, NSString *pwd) {
        [lockVC dismiss:1.0f];
        if (successBlock) {
            successBlock(pwd);
        }
        //用户信息更新
        NSMutableDictionary *para = [NSMutableDictionary new];
        [para setObject:@(1) forKey:@"msg_hidden"];
        [QAModuleService updateUserInfoWithPara:para success:^(QAResponseModel *response) {
            NSLog(@"应用锁日志 更新用户信息成功，准备回调");
            QAUserInfoModel *userInfo = WCICache.user;
            userInfo.msg_hidden = @"1";
            WCICache.user = userInfo;
        } failure:^(QAResponseModel *response) {
            NSLog(@"应用锁日志 更新用户信息失败");
        }];
    }];
}

+ (void)showModifyLockVCInVC:(UIViewController *)viewController forgetPwdBlock:(void(^)(void))forgetPwdBlock{
    __weak typeof (self) weakSelf = self;
    [MOLockViewController showModifyLockVCInVC:viewController forgetPwdBlock:^{
        [weakSelf clearAboutPasswordLocalValue];
        if (forgetPwdBlock) {
            forgetPwdBlock();
        }
    } successBlock:^(MOLockViewController *lockVC, NSString *pwd) {
        [lockVC dismiss:.5f];
    }];
}
@end
